package com.comleader.operator.service;

import static com.comleader.operator.pojo.entity.table.DictDataTableDef.DICT_DATA;
import static com.comleader.operator.pojo.entity.table.DictTypeTableDef.DICT_TYPE;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.comleader.operator.common.page.PageQuery;
import com.comleader.operator.common.util.DictCacheUtil;
import com.comleader.operator.mapper.DictTypeMapper;
import com.comleader.operator.pojo.entity.DictDataEntity;
import com.comleader.operator.pojo.entity.DictTypeEntity;
import com.comleader.operator.pojo.param.DictTypeParam;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 字典类型表 服务层实现。
 *
 * @author 连新景
 * @since 1.0
 */
@CacheConfig(cacheNames = "dictType")
@Service
public class DictTypeService extends ServiceImpl<DictTypeMapper, DictTypeEntity> {

    @Resource
    private DictDataService dictDataService;

    @PostConstruct
    public void init() {
        Map<String, List<DictDataEntity>> dictDataMap = CollStreamUtil.groupByKey(dictDataService.list(), DictDataEntity::getCode);
        dictDataMap.forEach((key, value) -> {
            DictCacheUtil.setDictCache(key, value.stream().sorted(Comparator.comparing(DictDataEntity::getSort)).collect(Collectors.toList()));
        });
    }

    public Page<DictTypeEntity> selectPage(DictTypeParam param) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(DICT_TYPE).and(DICT_TYPE.CODE.like(param.getCode(), If::hasText))
            .and(DICT_TYPE.NAME.like(param.getName(), If::hasText)).and(DICT_TYPE.TYPE.eq(param.getType())).orderBy(DICT_TYPE.ID.desc());
        return page(PageQuery.build(param), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateDictType(DictTypeEntity dictType) {
        DictTypeEntity oldDictType = getById(dictType.getId());
        boolean bn = false;
        // 如果编码修改了，需要修改字典数据表
        if (!Objects.equals(oldDictType.getCode(), dictType.getCode())) {
            DictDataEntity dictData = new DictDataEntity();
            dictData.setCode(dictType.getCode());
            bn = dictDataService.update(dictData, QueryWrapper.create().from(DICT_DATA).where(DICT_DATA.CODE.eq(oldDictType.getCode())));
        }
        updateById(dictType);
        if (bn) {
            List<DictDataEntity> dictDataList =
                dictDataService.list(QueryWrapper.create().from(DICT_DATA).where(DICT_DATA.CODE.eq(dictType.getCode())).orderBy(DICT_DATA.SORT.asc()));
            if (CollectionUtil.isNotEmpty(dictDataList)) {
                DictCacheUtil.setDictCache(dictType.getCode(), dictDataList);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Integer id) {
        DictTypeEntity dictType = getById(id);
        dictDataService.deleteByCode(dictType.getCode());
        DictCacheUtil.deleteCache(dictType.getCode());
        return removeById(id);
    }

    /**
     * @param dictType
     * @return boolean
     * @Description 校验字典code是否唯一
     * @Auhtor 连新景
     * @Date 2024/07/16 16:27
     */
    public boolean checkDictCodeUnique(DictTypeEntity dictType) {
        DictTypeEntity dictTypeEntity = getOne(QueryWrapper.create().where(DICT_TYPE.CODE.eq(dictType.getCode())));
        return dictTypeEntity == null || dictTypeEntity.getId().equals(dictType.getId());
    }

}